package com.ktjy.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjy.pojo.SysUser;
import com.ktjy.pojo.vo.R;
import com.ktjy.service.SysUserService;
import com.ktjy.util.Constants;
import com.ktjy.util.exception.LoginException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.AbstractController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@CrossOrigin(origins = "*")
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private SysUserService sysUserService;


    @RequestMapping("/login")
    public String login() {
        return "login";
    }


    @ResponseBody
    @RequestMapping("/doLogin")
    public R doLogin(@RequestBody SysUser sysUser, HttpSession session) throws LoginException {
        SysUser user = null;
        if (sysUser.getAccount().length() < 1 || sysUser.getAccount() == null) {
            return R.fail();
        } else {
            user = sysUserService.getSysUserByAccountBiz(sysUser.getAccount());
            if (user == null) {
                logger.info(sysUser.getAccount() + "用户不存在");
                //用户不存在
                //return forward("error.jsp");
                //throw new RuntimeException("用户不存在");
                return R.fail();
            } else if (!user.getPassword().equals(sysUser.getPassword())) {
                //密码不正确
                logger.info(sysUser.getAccount() + "密码错误");
                return R.fail();
            } else {
                logger.info(sysUser.getAccount() + "登录成功");
                //验证成功设置会话
                setSession(Constants.SESSION_USER, user);
                return R.ok(user);
            }
        }
    }

    //tomcat web 容器
    @RequestMapping("/index")
    public String index(HttpServletRequest request, Model model, HttpSession session) {
        //在springMVC controller获取spring容器
        ApplicationContext context =
                (ApplicationContext) request.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            System.out.println(beanDefinitionName);
        }
        return "index";
    }


    @RequestMapping("/list")
    public String list(Model model, HttpSession session) {
        List<SysUser> list = sysUserService.getSysUserListBiz(new SysUser());
        model.addAttribute("list", list);
        return "list";
    }

    @ResponseBody
    @RequestMapping(value = "/listjson")
    public List listjson() {
        List<SysUser> list = sysUserService.getSysUserListBiz(new SysUser());
        //return JSON.toJSONString(list);
        return list;
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        //session.invalidate();
        HttpSession session = request.getSession();

        return "redirect:/login";
    }

    @ResponseBody
    @RequestMapping("/findByAccount")
    public String findByAccount(String account) {
        SysUser sysUser = sysUserService.getSysUserByAccountBiz(account);
        Map<String, Object> map = new HashMap<>();
        if (sysUser != null) {
            map.put("exist", 1);
        } else {
            map.put("exist", 0);
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("/add")
    public String add() {
        return "add";
    }


    @RequestMapping("/doAdd")
    public String doAdd(SysUser sysUser) {
        int count = sysUserService.addBiz(sysUser);
        if (count > 0) {
            return "redirect:/user/list";
        } else {
            return "redirect:/error.jsp?msg=addException";
        }
    }


//    @ExceptionHandler(value = RuntimeException.class)
//    public String handleArithmeticException(RuntimeException e) {
//        getHttpServletRequest().setAttribute("msg", e);
//        return "500";
//    }
}
